package com.example.link.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.example.common.common.config.filter.UserContext;
import com.example.link.entity.LinkGroup;
import com.example.link.mapper.LinkGroupMapper;
import com.example.link.model.CreateLinkGroupDTO;
import com.example.link.model.LinkGroupVO;
import com.example.link.service.LinkGroupService;
import com.example.link.entity.ShortLink;
import lombok.RequiredArgsConstructor;
import com.example.link.mapper.ShortLinkMapper;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * @author qwert
 * @version 1.0.0
 * @create 2025/8/17 20:06
 **/
@Service
@RequiredArgsConstructor
public class LinkGroupServiceImpl implements LinkGroupService {

    private final LinkGroupMapper linkGroupMapper;
    private final ShortLinkMapper shortLinkMapper;

    @Override
    public List<LinkGroupVO> getLinkGroup(String userId) {
        List<LinkGroupVO> linkGroupVOS = new ArrayList<>();
        // 查询用户的分组列表，如果没有分组创建“默认分组”
        List<LinkGroup> linkGroups = linkGroupMapper.queryLinkGroupByUserId(userId);
        if (CollUtil.isEmpty(linkGroups)) {
            LinkGroup defaultLinkGroup = LinkGroup.builder()
                    .groupId(UUID.randomUUID().toString())
                    .name("默认分组")
                    .userId(UserContext.getCurrentUser().getUserId())
                    .description("default")
                    .build();
            linkGroupMapper.createLinkGroup(defaultLinkGroup);
            LinkGroupVO linkGroupVO = BeanUtil.toBean(defaultLinkGroup, LinkGroupVO.class);
            linkGroupVOS.add(linkGroupVO);
        } else {
            for (LinkGroup linkGroup : linkGroups) {
                List<ShortLink> shortLinks = shortLinkMapper.queryLinkCountByGroupId(linkGroup.getGroupId());
                LinkGroupVO linkGroupVO = BeanUtil.toBean(linkGroup, LinkGroupVO.class);
                linkGroupVO.setShortLinkCount(shortLinks.size());
                linkGroupVOS.add(linkGroupVO);
            }
        }
        // 查询分组下，短链数量
        return linkGroupVOS;
    }

    @Override
    public void createLinkGroup(CreateLinkGroupDTO createLinkGroupDTO) {
        String groupName = createLinkGroupDTO.getName();
        LinkGroup existLinkGroup = linkGroupMapper.queryLinkGroupByName(groupName);

        if (existLinkGroup != null) {
            throw new RuntimeException("分组名称重复");
        }

        LinkGroup linkGroup = LinkGroup.builder()
                .groupId(UUID.randomUUID().toString())
                .name(groupName)
                .userId(UserContext.getCurrentUser().getUserId())
                .description("default")
                .build();
        linkGroupMapper.createLinkGroup(linkGroup);
    }
}
